<template>
  <div class="PartyMemberTable-container">
    <searchData v-if="useSearch" :showTitleName="false" :searchData="searchArr" @search="handleSearch"></searchData>
    <div class="pub-table-action-btn">
      <a-button v-if="!isDisabled" type="primary" @click="visibleState.showMember = true">
        {{ btnText }}
      </a-button>
    </div>
    <s-table
      ref="table"
      row-key="id"
      :columns="useSearch ? searchColumn : columns"
      :data="loadData"
      show-size-changer
      show-quick-jumper
      show-pagination="auto"
      :useCache="false"
    >
      <template slot="learningStatus" slot-scope="text, record">
        {{ filterStatus(text) }}
      </template>
      <template slot="action" slot-scope="text, record">
        <div v-if="!isDisabled" class="pub-table-list-action">
          <span @click="deleteMember(record)">删除</span>
        </div>
      </template>
    </s-table>
    <PartyMemberModal
      v-if="visibleState.showMember"
      :visible.sync="visibleState.showMember"
      @ok="handleConfirmMember"
    />
  </div>
</template>

<script>
import PartyMemberModal from './PartyMemberModal.vue'
import { STable } from '@/components'

const LEARNING_STATUS_MAP = {
  1: '已学习',
  2: '未学习'
}

const searchArr = [
  {
    name: '党员名称',
    value: 'partyMemberName',
    type: 'input'
  },
  {
    name: '学习情况',
    value: 'learningStatus',
    type: 'select',
    data: Object.keys(LEARNING_STATUS_MAP).map(key => {
      return {
        label: LEARNING_STATUS_MAP[key],
        value: key
      }
    })
  }
]

const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '党员名称',
    dataIndex: 'partyMemberName'
  },
  {
    title: '所属党支部',
    dataIndex: 'partyOrgName'
  },
  {
    title: '员工编号',
    dataIndex: 'employeeNum'
  },
  {
    title: '手机号码',
    dataIndex: 'phone'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

const searchColumn = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '党员名称',
    dataIndex: 'partyMemberName'
  },
  {
    title: '所属党支部',
    dataIndex: 'partyOrgName'
  },
  {
    title: '学习状态',
    dataIndex: 'learningStatus',
    scopedSlots: { customRender: 'learningStatus' }
  },
  {
    title: '学习时间',
    dataIndex: 'learningTime'
  },
  {
    title: '员工编号',
    dataIndex: 'employeeNum'
  },
  {
    title: '手机号码',
    dataIndex: 'phone'
  }
]
export default {
  name:'a'+ Date.now(),
  components: {
    PartyMemberModal,
    STable
  },
  props: {
    // 请求表格数据的接口
    requestFn: {
      type: Function,
      require: true,
      default: null
    },
    // 请求参数
    requestArgs: {
      type: Object,
      default() {
        return {}
      }
    },
    // 组件模式 'add' | 'edit' | 'look' 分别采用不同的逻辑
    mode: {
      type: String,
      require: true,
      default: 'add'
    },
    // 按钮文本
    btnText: {
      type: String,
      default: '新增学习人员'
    },
    // 是否使用搜索项，如果使用的话
    useSearch: {
      type: Boolean,
      default: false
    },
    // 需要转换数据的字段Key，用于转换从modal选择的数据，默认选择ID字段
    convertKey: {
      type: String,
      default: 'id'
    }
  },
  data() {
    return {
      searchColumn,
      queryParam: {},
      searchArr,
      originMemberList: [], // 接口返回的人员数据
      realMemberList: [], // 接口返回的人员和手动添加的人员去重之后的数据
      memberList: [], // 手动添加的学习人员
      deletedMemberList: [], // 记录已删除人员
      columns,
      visibleState: {
        showMember: false
      }
    }
  },
  computed: {
    isDisabled() {
      return this.mode === 'look'
    }
  },
  methods: {
    filterStatus(val) {
      return LEARNING_STATUS_MAP[val] || ''
    },
    handleSearch(val = {}) {
      this.queryParam = {
        ...val
      }
      this.refreshTable()
    },
    refreshTable() {
      this.$refs.table.refresh(true)
    },
    /**
     * 获取变动的数据
     * @returns {Object} { addList: Array<Object>, delList: Array<Object> } 返回对象里包括，新增对象数组、删除对象数组
     */
    getChangedData() {
      const delMembers =
        this.mode === 'add'
          ? []
          : this.originMemberList.filter((item) => {
              const index = this.realMemberList.findIndex(
                (realMember) => realMember.partyMemberId === item.partyMemberId
              )
              return index < 0
            })
      return {
        addList: this.memberList,
        delList: delMembers,
        allList: this.mode === 'add' ? this.memberList : this.realMemberList
      }
    },
    /**
     * 从表格删除学习人员
     */
    deleteMember(data) {
      const list = this.mode === 'add' ? this.memberList : this.realMemberList
      const index = list.findIndex((item) => item.partyMemberId === data.partyMemberId)
      list.splice(index, 1)
      this.deletedMemberList.push({ ...data })
      const addIndex = this.memberList.findIndex((item) => item.partyMemberId === data.partyMemberId)
      if (addIndex > -1) {
        this.memberList.splice(addIndex, 1)
      }
      this.$refs.table.refresh(false)
    },
    handleConfirmMember(list) {
      // 统一字段为 partyMemberId
      this.memberList = this.memberList.concat(
        list.map((item) => {
          item.partyMemberId = item[this.convertKey]
          item.partyMemberName = item.userName
          const deleteIndex = this.deletedMemberList.findIndex(
            (deleteMember) => deleteMember.partyMemberId === item.partyMemberId
          )
          if (deleteIndex > -1) {
            this.deletedMemberList.splice(deleteIndex, 1)
          }
          return item
        }).filter(item => {
          // 去重处理，防止添加到已存在的人
          return this.realMemberList.findIndex(member => member.partyMemberId === item.partyMemberId) < 0
        })
      )
      this.$refs.table.refresh(false)
      this.visibleState.showMember = false
      this.$emit('confirm')
    },
    /**
     * 学习人员信息列表(前端进行分页处理)
     */
    async loadData(params) {
      // 如果使用search的话，则不使用前端分页
      if (this.useSearch) {
        return this.requestFn({ ...params, query: { ...this.requestArgs.query, ...this.queryParam } })
      }
      try {
        const pageNo = params.pageNo || 1
        const pageSize = params.pageSize
        if (this.mode === 'add') {
          const list = this.memberList.slice((pageNo - 1) * pageSize, pageNo * pageSize)
          this.realMemberList = this.memberList // 表格所有的数据
          return Promise.resolve({
            data: list,
            currentPage: pageNo,
            totalSize: this.memberList.length
          })
        }
        const requestParams = { needCount: false, ...this.requestArgs }
        return this.requestFn(requestParams).then((res) => {
          this.originMemberList = res.data || [] // 保存接口返回的原数据
          const realList = this.originMemberList
            .filter((item) => {
              return this.memberList.findIndex((member) => member.partyMemberId === item.partyMemberId) < 0
            })
            .filter((item) => {
              const index = this.deletedMemberList.findIndex((member) => member.partyMemberId === item.partyMemberId)
              return index < 0
            })
            .concat(this.memberList)
          this.realMemberList = realList // 编辑时，表格所有的数据
          this.$emit('reload')
          return {
            data: realList.slice((pageNo - 1) * pageSize, pageNo * pageSize),
            currentPage: pageNo,
            totalSize: realList.length
          }
        })
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>

<style>
</style>